/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PanelEntrada.java
 *
 * Created on 08/09/2011, 18:26:49
 */
package modules.enderecamento.gui.jpanel;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import javax.swing.JFormattedTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.MaskFormatter;
import modules.enderecamento.exception.EspacoExcedidoPaleteException;
import modules.enderecamento.exception.EspacoExcedidoRuaException;
import modules.enderecamento.facade.WMSFacade;
import modules.enderecamento.gui.custom.LimitedIntegerJTextField;
import modules.enderecamento.gui.custom.WMSJComboBox;
import modules.enderecamento.models.dto.Enderecamento;
import modules.enderecamento.models.dto.Entrada;
import modules.enderecamento.models.dto.Palete;
import modules.enderecamento.models.dto.Produto;
import modules.enderecamento.models.dto.Rua;
import modules.enderecamento.models.dto.TiposMovimento;
import modules.enderecamento.security.WMSSession;
import modules.enderecamento.util.BoxPanel;
import modules.enderecamento.util.Funcoes;
import modules.enderecamento.validation.Validation;

/**
 *
 * @author Clezio
 */
public class PanelEntrada extends javax.swing.JPanel {

    private WMSFacade wmsFacade;
    MaskFormatter formatoData;

    /** Creates new form PanelEntrada */
    public PanelEntrada() {
        try {
            formatoData = new MaskFormatter("##/##/####");
        } catch (Exception erro) {
        }

        initComponents();
        wmsFacade = new WMSFacade();
        //Define layout table
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(44);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(116);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(52);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(144);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(306);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(48);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        tfRua = new modules.enderecamento.gui.custom.WMSJTextField();
        wMSLabel1 = new modules.enderecamento.gui.custom.WMSLabel();
        wMSLabel2 = new modules.enderecamento.gui.custom.WMSLabel();
        tfPalete = new LimitedIntegerJTextField(10);
        wMSLabel3 = new modules.enderecamento.gui.custom.WMSLabel();
        tfCodigo = new modules.enderecamento.gui.custom.WMSJTextField();
        tfDescricao = new modules.enderecamento.gui.custom.WMSJTextField();
        wMSLabel4 = new modules.enderecamento.gui.custom.WMSLabel();
        btnAdicionar = new modules.enderecamento.gui.custom.WMSJButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new modules.enderecamento.gui.custom.WMSJTable();
        wMSLabel5 = new modules.enderecamento.gui.custom.WMSLabel();
        tfConfirmar = new modules.enderecamento.gui.custom.WMSJTextField();
        wMSLabel6 = new modules.enderecamento.gui.custom.WMSLabel();
        wMSLabel7 = new modules.enderecamento.gui.custom.WMSLabel();
        tfData = new JFormattedTextField(formatoData);
        wMSLabel8 = new modules.enderecamento.gui.custom.WMSLabel();
        tfQuantidade = new LimitedIntegerJTextField(10);
        tfRequisicao = new LimitedIntegerJTextField(10);
        cbTiposMovimento = new modules.enderecamento.gui.custom.WMSJComboBox();
        wMSLabel9 = new modules.enderecamento.gui.custom.WMSLabel();

        setBackground(new java.awt.Color(238, 238, 238));
        addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                formAncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Entrada - endereçamento");

        tfRua.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfRuaActionPerformed(evt);
            }
        });
        tfRua.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfRuaFocusLost(evt);
            }
        });
        tfRua.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfRuaKeyPressed(evt);
            }
        });

        wMSLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel1.setText("Data:");

        wMSLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel2.setText("Palete:");

        tfPalete.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfPaleteFocusLost(evt);
            }
        });
        tfPalete.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfPaleteKeyPressed(evt);
            }
        });

        wMSLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel3.setText("Código:");

        tfCodigo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfCodigoFocusLost(evt);
            }
        });
        tfCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfCodigoKeyPressed(evt);
            }
        });

        tfDescricao.setEditable(false);
        tfDescricao.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfDescricaoKeyPressed(evt);
            }
        });

        wMSLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel4.setText("Requisiçao:");

        btnAdicionar.setText("Registrar");
        btnAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAdicionarActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Rua", "Palete", "Código", "Descrição", "Qtde"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        wMSLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel5.setText("Confimar dados:");

        tfConfirmar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfConfirmarKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tfConfirmarKeyReleased(evt);
            }
        });

        wMSLabel6.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        wMSLabel6.setText("(S) ou (N)");

        wMSLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel7.setText("Rua:");

        tfData.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfDataKeyPressed(evt);
            }
        });

        wMSLabel8.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel8.setText("Quantidade:");

        tfQuantidade.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfQuantidadeKeyPressed(evt);
            }
        });

        tfRequisicao.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfRequisicaoFocusLost(evt);
            }
        });
        tfRequisicao.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfRequisicaoKeyPressed(evt);
            }
        });

        cbTiposMovimento.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbTiposMovimento.setFont(new java.awt.Font("Tahoma", 1, 10));
        cbTiposMovimento.setMaximumSize(new java.awt.Dimension(51, 18));
        cbTiposMovimento.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbTiposMovimentoItemStateChanged(evt);
            }
        });
        cbTiposMovimento.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cbTiposMovimentoKeyPressed(evt);
            }
        });

        wMSLabel9.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel9.setText("Natureza:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 780, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap())
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 769, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap()))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(23, 23, 23)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addGroup(layout.createSequentialGroup()
                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                                .addComponent(wMSLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                                    .addComponent(wMSLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                    .addComponent(wMSLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                .addComponent(tfData)
                                                .addComponent(tfRua, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)))
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(wMSLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addComponent(tfPalete, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(wMSLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)
                                            .addComponent(wMSLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(tfRequisicao, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(6, 6, 6)
                                                .addComponent(tfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addComponent(cbTiposMovimento, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(wMSLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(btnAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(tfConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(4, 4, 4)
                                                .addComponent(wMSLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(23, 23, 23)
                                        .addComponent(wMSLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(tfQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(273, 273, 273)))
                        .addGap(306, 306, 306))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wMSLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbTiposMovimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wMSLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfRua, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(wMSLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tfPalete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(wMSLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(wMSLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(tfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wMSLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfRequisicao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wMSLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(tfConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(2, 2, 2)
                            .addComponent(wMSLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(wMSLabel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void tfRuaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfRuaKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfPalete.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfRua.setText("");
            tfData.requestFocus();
        }
}//GEN-LAST:event_tfRuaKeyPressed

    private void tfPaleteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfPaleteKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfCodigo.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfPalete.setText("");
            tfRua.requestFocus();
        }
    }//GEN-LAST:event_tfPaleteKeyPressed

    private void tfCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfCodigoKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            if(tfRequisicao.isEditable()){
                tfRequisicao.requestFocus();
            }else{
                tfQuantidade.requestFocus();
            }
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfCodigo.setText("");
            tfPalete.requestFocus();
        }
    }//GEN-LAST:event_tfCodigoKeyPressed

    private void tfDescricaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfDescricaoKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfDescricaoKeyPressed

    private void btnAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarActionPerformed
        String confirm = tfConfirmar.getText();
        if (confirm.toUpperCase().equals("S")) {
            save();
        } else if (confirm.toUpperCase().equals("N")) {
            clearFields();
        } else {
            BoxPanel.showMessageDialog(null, "A confirmação é um campo obrigatório.");
            tfConfirmar.setText("");
            tfConfirmar.requestFocus();
        }
}//GEN-LAST:event_btnAdicionarActionPerformed

    private void tfRuaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfRuaActionPerformed
    }//GEN-LAST:event_tfRuaActionPerformed

    private void tfRuaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfRuaFocusLost
        if (tfRua.getText().length() > 0) {
            Rua rua = wmsFacade.obterRuaByName(tfRua.getText());
            if (rua == null) {
                BoxPanel.showMessageDialog(null, "Rua não encontrada");
                tfRua.setText("");
                tfRua.requestFocus();
            } else {
                tfPalete.requestFocus();
            }
        }
    }//GEN-LAST:event_tfRuaFocusLost

    private void tfPaleteFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfPaleteFocusLost
        processaDadosPalete();
    }//GEN-LAST:event_tfPaleteFocusLost

    private void tfCodigoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfCodigoFocusLost
        if (tfCodigo.getText().length() > 0) {
            Produto produto = wmsFacade.obterProdutoByCodigo(tfCodigo.getText());
            if (produto == null) {
                BoxPanel.showMessageDialog(null, "Produto não encontrado");
                tfCodigo.setText("");
                tfCodigo.requestFocus();
                tfDescricao.setText("");
            } else {
                tfDescricao.setText(produto.getDescricao());
                if(tfRequisicao.isEditable()){
                    tfRequisicao.requestFocus();
                }else{
                    tfQuantidade.requestFocus();
                }
            }
        } else {
            tfDescricao.setText("");
        }
    }//GEN-LAST:event_tfCodigoFocusLost

    private void tfConfirmarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfConfirmarKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            String confirm = tfConfirmar.getText();
            if (confirm.toUpperCase().equals("S")) {
                save();
            } else if (confirm.toUpperCase().equals("N")) {
                clearFields();
            } else {
                BoxPanel.showMessageDialog(null, "A confirmação é um campo obrigatório.");
                tfConfirmar.setText("");
                tfConfirmar.requestFocus();
            }
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfConfirmar.setText("");
            tfQuantidade.requestFocus();
        }
    }//GEN-LAST:event_tfConfirmarKeyPressed

    private void tfConfirmarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfConfirmarKeyReleased
        if (tfConfirmar.getText().length() > 0) {
            tfConfirmar.setText(tfConfirmar.getText().substring(0, 1));
        }
    }//GEN-LAST:event_tfConfirmarKeyReleased

    private void formAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_formAncestorAdded
        clearAllFields();
        tfData.setText(Funcoes.dateToString(new Date()));
        preencheCbTiposMovimento(wmsFacade.obterTiposMovimentos("from TiposMovimento where natureza = 'E' order by nome"));
    }//GEN-LAST:event_formAncestorAdded

    private void tfDataKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfDataKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfRua.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfData.setText("");
            cbTiposMovimento.requestFocus();
        }
    }//GEN-LAST:event_tfDataKeyPressed

    private void tfQuantidadeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfQuantidadeKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfConfirmar.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            if(tfRequisicao.isEditable()){
                tfRequisicao.requestFocus();
            }else{
                tfCodigo.requestFocus();
            }
            tfQuantidade.setText("");
        }
    }//GEN-LAST:event_tfQuantidadeKeyPressed

    private void tfRequisicaoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfRequisicaoFocusLost
        // TODO add your handling code here:
    }//GEN-LAST:event_tfRequisicaoFocusLost

    private void tfRequisicaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfRequisicaoKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfQuantidade.requestFocus();
        } else if (evt.getKeyCode() == evt.VK_ESCAPE) {
            tfCodigo.requestFocus();
            tfRequisicao.setText("");
        }
    }//GEN-LAST:event_tfRequisicaoKeyPressed

    private void cbTiposMovimentoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbTiposMovimentoItemStateChanged
        checaCbTipoMovimento();
    }//GEN-LAST:event_cbTiposMovimentoItemStateChanged

    private void cbTiposMovimentoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cbTiposMovimentoKeyPressed
        if (evt.getKeyCode() == evt.VK_ENTER) {
            tfData.requestFocus();
        }
    }//GEN-LAST:event_cbTiposMovimentoKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private modules.enderecamento.gui.custom.WMSJButton btnAdicionar;
    private modules.enderecamento.gui.custom.WMSJComboBox cbTiposMovimento;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private modules.enderecamento.gui.custom.WMSJTable jTable1;
    private modules.enderecamento.gui.custom.WMSJTextField tfCodigo;
    private modules.enderecamento.gui.custom.WMSJTextField tfConfirmar;
    private javax.swing.JTextField tfData;
    private modules.enderecamento.gui.custom.WMSJTextField tfDescricao;
    private modules.enderecamento.gui.custom.WMSJTextField tfPalete;
    private modules.enderecamento.gui.custom.WMSJTextField tfQuantidade;
    private modules.enderecamento.gui.custom.WMSJTextField tfRequisicao;
    private modules.enderecamento.gui.custom.WMSJTextField tfRua;
    private modules.enderecamento.gui.custom.WMSLabel wMSLabel1;
    private modules.enderecamento.gui.custom.WMSLabel wMSLabel2;
    private modules.enderecamento.gui.custom.WMSLabel wMSLabel3;
    private modules.enderecamento.gui.custom.WMSLabel wMSLabel4;
    private modules.enderecamento.gui.custom.WMSLabel wMSLabel5;
    private modules.enderecamento.gui.custom.WMSLabel wMSLabel6;
    private modules.enderecamento.gui.custom.WMSLabel wMSLabel7;
    private modules.enderecamento.gui.custom.WMSLabel wMSLabel8;
    private modules.enderecamento.gui.custom.WMSLabel wMSLabel9;
    // End of variables declaration//GEN-END:variables

    private void save() {
        int quantidade = 0;
        try{
            quantidade = Integer.parseInt(tfQuantidade.getText());
        }catch(Exception e){}
        
        Date date = null;
        try {
            date = Funcoes.stringToDate(tfData.getText());
            if(date.after(new Date())){
                Validation.getInstance().addErros("data", "A data não pode ser superior a data atual.");
            }
        } catch (ParseException ex) {
            if(tfData.getText().equals("  /  /    ")){
                Validation.getInstance().addErros("data", "Data é um campo obrigatório.");
            }else{
                Validation.getInstance().addErros("data", "A data informada é inválida.");
            }
        }
        if(tfRua.getText().length() == 0){
            Validation.getInstance().addErros("rua", "Rua é um campo obrigatório.");
        }
        if(tfPalete.getText().length() == 0){
            Validation.getInstance().addErros("palete", "Palete é um campo obrigatório.");
        }
        if(tfCodigo.getText().length() == 0){
            Validation.getInstance().addErros("codigo", "Código é um campo obrigatório.");
        }
        if(quantidade < 1){
            Validation.getInstance().addErros("quantidade", "Quantidade inválida.");
        }
        if(tfRequisicao.getText().length() == 0 && tfRequisicao.isEditable()){
            Validation.getInstance().addErros("requisicao", "Requisição é um campo obrigatório.");
        }

        if(Validation.getInstance().hasErrors()){
            BoxPanel.showMessageError(Funcoes.getListErros(Validation.getInstance().getErros()));
            return;
        }

        Palete palete = wmsFacade.obterPaleteById(Integer.parseInt(tfPalete.getText()));
        Produto produto = wmsFacade.obterProdutoByCodigo(tfCodigo.getText());
        Rua rua = wmsFacade.obterRuaByName(tfRua.getText());
        if (palete == null) {
            BoxPanel.showMessageDialog(null, "Palete inválido");
            return;
        }
        if (rua == null) {
            BoxPanel.showMessageDialog(null, "Rua inválida");
            return;
        }
        if (produto == null) {
            BoxPanel.showMessageDialog(null, "Produto inválido");
            return;
        }
        Integer requisicao = null;
        try{
            requisicao = Integer.parseInt(tfRequisicao.getText());
        }catch(Exception e){}
        

        //####
        Entrada entrada = new Entrada();
        palete.setRua(rua);
        entrada.setPalete(palete);
        entrada.setProduto(produto);
        entrada.setRua(rua);
        entrada.setRequisicao(requisicao);
        entrada.setQuantidade(quantidade);
        entrada.setDataEntrada(date);
        entrada.setUsuario(WMSSession.getInstance().getUser());
        entrada.setTiposMovimento((TiposMovimento) cbTiposMovimento.getSelectedItem());
        entrada.setCancelado(false);
        try {
            if (wmsFacade.registrarEntrada(entrada, false)) {
                BoxPanel.showMessageDialog(null, "Entrada registrada com sucesso!");
                clearFields();
                listarEnderecamento(wmsFacade.getListEnderecamentoByPalete(new Palete(Integer.parseInt(tfPalete.getText()))));
            }
        } catch (EspacoExcedidoPaleteException ex) {
            BoxPanel.showMessageDialog(null, ex.getMessage());
            tfConfirmar.setText("");
            tfConfirmar.requestFocus();
        } catch (EspacoExcedidoRuaException ex) {
            BoxPanel.showMessageDialog(null, ex.getMessage());
        }
    }

    private void clearFields() {
        tfCodigo.setText("");
        tfDescricao.setText("");
        tfQuantidade.setText("");
        tfConfirmar.setText("");
        tfRequisicao.setText("");
        tfCodigo.requestFocus();
    }

    private void clearAllFields() {
        clearFields();
        tfRua.setText("");
        tfPalete.setText("");
        tfRua.requestFocus();
    }

    private void listarEnderecamento(List<Enderecamento> enderecamentos) {
        if (enderecamentos != null) {
            DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
            modelo.setNumRows(0);
            for (int i = 0; i < enderecamentos.size(); i++) {
                int id = enderecamentos.get(i).getId();
                String rua = enderecamentos.get(i).getPalete().getRua().getNome();
                Integer palete = enderecamentos.get(i).getPalete().getId();
                String codigo = enderecamentos.get(i).getProduto().getCodigo();
                String descricao = enderecamentos.get(i).getProduto().getDescricao();
                Integer quantidade = enderecamentos.get(i).getQuantidade();
                modelo.addRow(new Object[]{
                            id, rua, palete, codigo, descricao, quantidade
                        });
            }
        }
    }

    private void processaDadosPalete() {
        if (tfPalete.getText().length() > 0) {
            Palete palete = wmsFacade.obterPaleteById(Integer.parseInt(tfPalete.getText()));
            if (palete == null) {
                BoxPanel.showMessageDialog(null, "Palete não encontrado");
                tfPalete.setText("");
                tfPalete.requestFocus();
            } else {
                if (palete.getRua() != null) {
                    if (!palete.getRua().getNome().equals(tfRua.getText().toUpperCase())) {
                        String nameRuaOrigem = palete.getRua().getNome();
                        String nameRuaDestino = tfRua.getText().toUpperCase();
                        if (BoxPanel.showConfirmDialog(null, "O Palete informado está localizado na rua " + nameRuaOrigem
                                + "\r\nDeseja mover para " + nameRuaDestino + "?") == 0) {
                            Rua ruaDestino = wmsFacade.obterRuaByName(nameRuaDestino);
                            try {
                                if (wmsFacade.moverPalete(palete, ruaDestino)) {
                                    BoxPanel.showMessageDialog(null, "Palete movido com sucesso.");
                                    tfCodigo.requestFocus();
                                } else {
                                    tfPalete.setText("");
                                    tfPalete.requestFocus();
                                }
                            } catch (EspacoExcedidoRuaException ex) {
                                BoxPanel.showMessageDialog(null, ex.getMessage());
                                tfPalete.setText("");
                                tfPalete.requestFocus();
                            }

                        } else {
                            tfPalete.setText("");
                            tfPalete.requestFocus();
                        }
                    } else {
                        tfCodigo.requestFocus();
                    }
                } else {
                    tfCodigo.requestFocus();
                }
                if (tfPalete.getText().length() > 0) {
                    listarEnderecamento(wmsFacade.getListEnderecamentoByPalete(new Palete(Integer.parseInt(tfPalete.getText()))));
                }
            }
        }
    }

    private void preencheCbTiposMovimento(List<TiposMovimento> lista){
        cbTiposMovimento.removeAllItems();
        for (int i= 0; i < lista.size(); i++) {
            cbTiposMovimento.addItem(lista.get(i));
            if(lista.get(i).getId() == 1){
                cbTiposMovimento.setSelectedIndex(i);
            }
        }
        checaCbTipoMovimento();
    }

    private void checaCbTipoMovimento(){
        TiposMovimento tiposMovimento = (TiposMovimento) cbTiposMovimento.getSelectedItem();
        if(tiposMovimento != null){
            if(tiposMovimento.isIncrementaSaldo()){
//                tfData.setEditable(true);
                tfRequisicao.setEditable(true);
//                tfData.setText(Funcoes.dateToString(new Date()));
            }else{
//                tfData.setText("");
                tfRequisicao.setText("");
//                tfData.setEditable(false);
                tfRequisicao.setEditable(false);
            }
            tfData.requestFocus();
        }
    }
}
